package hu.debrecen.adastra.card.web.resolver;

import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.service.SocialUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

public class AccountArgumentResolver extends AutowiredHandlerAnnotationArgumentResolver {

	private static final Logger LOGGER = LoggerFactory.getLogger(AccountArgumentResolver.class);

	private final SocialUserService socialUserService;

	public AccountArgumentResolver(final SocialUserService socialUserService) {
		this.socialUserService = socialUserService;
	}

	@Override
	public boolean supportsParameter(final MethodParameter paramMethodParameter) {
		return super.supportsParameter(paramMethodParameter) && paramMethodParameter.getParameterType().equals(Account.class);
	}

	@Override
	public Object resolveArgument(final MethodParameter paramMethodParameter, final ModelAndViewContainer paramModelAndViewContainer, final NativeWebRequest paramNativeWebRequest,
			final WebDataBinderFactory paramWebDataBinderFactory) throws Exception {
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		AccountArgumentResolver.LOGGER.trace("Resove account by name({})", name);
		return this.socialUserService.getAccount(name);
	}

}
